package cube.io.file;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件读取
 * 
 * @author abiao
 */
public abstract class FileReaderHandler<T> extends
        FileHandler<BufferedReader, T> {

    /**
     * 文件读取
     */
    public FileReaderHandler(String fileName) {
        super(fileName);
    }

    /**
     * 初始化
     */
    public BufferedReader init(String fileName) {
        BufferedReader bufferedReader = null;
        try {
            bufferedReader =
                    new BufferedReader(new InputStreamReader(
                            new FileInputStream(fileName)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return bufferedReader;
    }

    /**
     * 从缓存中读取行
     */
    protected List<String> readLines(BufferedReader br, final int size)
            throws IOException {
        List<String> lines = new ArrayList<String>();
        String line = null;
        for (int i = 0; i < size && (line = br.readLine()) != null; i++) {
            lines.add(line);
        }
        return lines;
    }

    /**
     * 从缓存中读取所有行
     */
    protected List<String> readLines(BufferedReader br) throws IOException {
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = br.readLine()) != null) {
            lines.add(line);
        }
        return lines;
    }
}
